import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from '../store';
import {
  fetchMaterials,
  createMaterial,
  updateMaterial,
  deleteMaterial,
  clearError,
  removeMaterialManual
} from '../store/slices/materialSlice';
import type {
  CreateMaterialRequest,
  UpdateMaterialRequest
} from '../api/types/material'; export const useMaterial = () => {
  const dispatch = useDispatch<AppDispatch>();
  const { materials, loading, error } = useSelector((state: RootState) => state.material);

  const getMaterials = useCallback(() => {
    return dispatch(fetchMaterials());
  }, [dispatch]);

  const addMaterial = useCallback((materialData: CreateMaterialRequest) => {
    return dispatch(createMaterial(materialData));
  }, [dispatch]);

  const modifyMaterial = useCallback((id: number, materialData: UpdateMaterialRequest) => {
    return dispatch(updateMaterial({ id, ...materialData }));
  }, [dispatch]);

  const removeMaterial = useCallback(async (materialId: number) => {
    try {
        const result = await dispatch(deleteMaterial(materialId)).unwrap();
      return result;
    } catch (error) {
     throw error;
    }
  }, [dispatch]);



  const resetError = useCallback(() => {
    dispatch(clearError());
  }, [dispatch]);

  const getMaterialById = useCallback((id: number) => {
    return materials.find(material => material.id === id);
  }, [materials]);

  return {
    // State
    materials,
    loading,
    error,

    // Actions
    getMaterials,
    addMaterial,
    modifyMaterial,
    removeMaterial,
    resetError,
    getMaterialById,
  };
};

export default useMaterial;